<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>电影信息</title>
</head>
<body>
<h1>恭喜你，<span th:text="${username}"></span> 管理员登录成功！</h1>
<a th:href="@{/adminSuccessPage(username=${username}, page=0, size=10)}">用户信息</a>
<a th:href="@{/adminTicketsPage(username=${username}, page=0, size=10)}">购票信息</a>
<a th:href="@{/adminMoviesPage(username=${username}, page=0, size=10)}">电影信息</a>
<a th:href="@{/adminGenersPage(username=${username}, page=0, size=10)}">类别信息</a>
<a th:href="@{/adminDirectorsPage(username=${username}, page=0, size=10)}">导演信息</a>
<a th:href="@{/adminActorsPage(username=${username}, page=0, size=10)}">演员信息</a>
<a th:href="@{/adminReviewsPage(username=${username}, page=0, size=10)}">评论信息</a>

<!-- 添加搜索框和搜索按钮 -->
<form id="searchForm">
    <input type="hidden" th:name="username" th:value="${username}">
    <input type="hidden" th:name="size" th:value="${pageSize}">
    <input type="hidden" th:name="page" th:value="0">
    <label for="searchMname">根据电影名搜索:</label>
    <input type="text" id="searchMname" name="mname">
    <input type="button" value="搜索" onclick="searchMovies()">
</form>

<h2>电影信息列表</h2>
<button id="addMovieBtn">新增电影</button>
<table>
    <thead>
    <tr>
        <th>电影编号</th>
        <th>电影名称</th>
        <th>上映时间</th>
        <th>片长</th>
        <th>评分</th>
        <th>投票数</th>
        <th>状态</th>
        <th>价格</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody id="movieTableBody">
    <tr th:each="movie : ${movies}">
        <td th:text="${movie.mid}"></td>
        <td th:text="${movie.mtitle}"></td>
        <td th:text="${movie.mdate}"></td>
        <td th:text="${movie.mruntime}"></td>
        <td th:text="${movie.rating}"></td>
        <td th:text="${movie.vote_count}"></td>
        <td th:text="${movie.status}"></td>
        <td th:text="${movie.price}"></td>
        <td>
            <button th:onclick="'deleteMovie(' + ${movie.mid} + ')'">删除</button>
            <!-- 修改此处 -->
            <button th:onclick="'showEditForm(' + ${movie.mid} + ')'">修改</button>
        </td>
    </tr>
    </tbody>
</table>

<!-- 新增电影表单 -->
<div id="addMovieForm" style="display: none;">
    <h3>新增电影</h3>
    <form id="addMovieFormData" th:action="@{/admin/addMovie}" method="post">
        <label for="addMtitle">电影名称:</label>
        <input type="text" id="addMtitle" name="mtitle" required><br>
        <label for="addMdate">上映时间:</label>
        <input type="text" id="addMdate" name="mdate"><br>
        <label for="addMruntime">片长:</label>
        <input type="text" id="addMruntime" name="mruntime"><br>
        <label for="addRating">评分:</label>
        <input type="text" id="addRating" name="rating"><br>
        <label for="addVoteCount">投票数:</label>
        <input type="text" id="addVoteCount" name="vote_count"><br>
        <label for="addStatus">状态:</label>
        <input type="text" id="addStatus" name="status"><br>
        <label for="addPrice">价格:</label>
        <input type="text" id="addPrice" name="price"><br>
        <button type="button" onclick="submitAddMovieForm()">提交</button>
        <button type="button" onclick="cancelAddMovieForm()">取消</button>
    </form>
</div>

<!-- 修改电影表单 -->
<div id="editMovieForm" style="display: none;">
    <h3>修改电影</h3>
    <form id="editMovieFormData">
        <input type="hidden" id="editMid" name="mid">
        <label for="editMtitle">电影名称:</label>
        <input type="text" id="editMtitle" name="mtitle" required><br>
        <label for="editMdate">上映时间:</label>
        <input type="text" id="editMdate" name="mdate"><br>
        <label for="editMruntime">片长:</label>
        <input type="text" id="editMruntime" name="mruntime"><br>
        <label for="editRating">评分:</label>
        <input type="text" id="editRating" name="rating"><br>
        <label for="editVoteCount">投票数:</label>
        <input type="text" id="editVoteCount" name="vote_count"><br>
        <label for="editStatus">状态:</label>
        <input type="text" id="editStatus" name="status"><br>
        <label for="editPrice">价格:</label>
        <input type="text" id="editPrice" name="price"><br>
        <button type="button" onclick="submitEditMovieForm()">提交</button>
        <button type="button" onclick="cancelEditMovieForm()">取消</button>
    </form>
</div>

<!-- 分页导航栏 -->
<div>
    <!-- 首页 -->
    <a th:href="@{/adminMoviesPage(username=${username}, page=0, size=${pageSize})}">首页</a>
    <!-- 上一页 -->
    <a th:if="${currentPage > 0}"
       th:href="@{/adminMoviesPage(username=${username}, page=${currentPage - 1}, size=${pageSize})}">上一页</a>

    <!-- 下一页 -->
    <a th:if="${currentPage < totalPages - 1}"
       th:href="@{/adminMoviesPage(username=${username}, page=${currentPage + 1}, size=${pageSize})}">下一页</a>

    <!-- 末页 -->
    <a th:href="@{/adminMoviesPage(username=${username}, page=${totalPages - 1}, size=${pageSize})}">末页</a>

    <!-- 显示当前页和总页数 -->
    <span>当前页: <span th:text="${currentPage + 1}"></span> / 总页数: <span th:text="${totalPages}"></span></span>
    <form th:action="@{/adminMoviesPage}" method="get">
        <input type="hidden" name="username" th:value="${username}">
        <input type="hidden" name="size" th:value="${pageSize}">
        <label for="pageNumber">跳转到页数:</label>
        <input type="number" id="pageNumber" name="page" min="0" th:max="${totalPages - 1}" required>
        <input type="submit" value="跳转">
    </form>
</div>

<script>

    // 显示新增表单
    document.getElementById('addMovieBtn').addEventListener('click', function() {
        document.getElementById('addMovieForm').style.display = 'block';
    });

    function cancelAddMovieForm() {
        document.getElementById('addMovieForm').style.display = 'none';
    }

    function searchMovies() {
        const mname = document.getElementById('searchMname').value;
        const username = document.querySelector('input[name="username"]').value;
        const size = document.querySelector('input[name="size"]').value;
        const page = document.querySelector('input[name="page"]').value;

        fetch(`/movie/searchMovie?mname=${mname}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const movies = data.movies;
                    const tableBody = document.getElementById('movieTableBody');
                    tableBody.innerHTML = '';

                    movies.forEach(movie => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${movie.mid}</td>
                            <td>${movie.mtitle}</td>
                            <td>${movie.mdate}</td>
                            <td>${movie.mruntime}</td>
                            <td>${movie.rating}</td>
                            <td>${movie.vote_count}</td>
                            <td>${movie.status}</td>
                            <td>${movie.price}</td>
                            <td>
                                <button onclick="deleteMovie(${movie.mid})">删除</button>
                                <button onclick="showEditForm(${movie.mid})">修改</button>
                            </td>
                        `;
                        tableBody.appendChild(row);
                    });
                } else {
                    alert(data.error);
                }
            })
            .catch(error => {
                alert('查询电影信息失败：' + error.message);
            });
    }
    // 新增 showEditForm 函数
    function showEditForm(mid) {
        // 显示修改表单
        document.getElementById('editMovieForm').style.display = 'block';

        // 发送请求获取电影信息
        fetch(`/movie/infoMovie?mid=${mid}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const movie = data.movies;
                    document.getElementById('editMid').value = movie.mid;
                    document.getElementById('editMtitle').value = movie.mtitle;
                    document.getElementById('editMdate').value = movie.mdate;
                    document.getElementById('editMruntime').value = movie.mruntime;
                    document.getElementById('editRating').value = movie.rating;
                    document.getElementById('editVoteCount').value = movie.vote_count;
                    document.getElementById('editStatus').value = movie.status;
                    document.getElementById('editPrice').value = movie.price;
                } else {
                    alert(data.error);
                }
            })
            .catch(error => {
                alert('查询电影信息失败：' + error.message);
            });
    }

    function cancelEditMovieForm() {
        document.getElementById('editMovieForm').style.display = 'none';
    }

    function submitEditMovieForm() {
        // 获取表单数据
        const form = document.getElementById('editMovieFormData');
        const formData = new FormData(form);

        // 发送 PUT 请求到后端
        fetch('/admin/updateMovie', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(Object.fromEntries(formData))
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('电影信息修改成功');
                    // 隐藏修改表单
                    document.getElementById('editMovieForm').style.display = 'none';
                    // 刷新电影列表，可根据实际情况修改
                    searchMovies();
                } else {
                    alert('电影信息修改失败：' + data.message);
                }
            })
            .catch(error => {
                alert('请求出错：' + error.message);
            });
    }
    function deleteMovie(mid) {
        if (confirm("确定要删除该电影吗？")) {
            fetch(`/admin/deleteMovie/${mid}`, {
                method: 'DELETE'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('电影删除成功');
                        // 刷新电影列表
                        searchMovies();
                    } else {
                        alert('电影删除失败：' + data.message);
                    }
                })
                .catch(error => {
                    alert('请求出错：' + error.message);
                });
        }
    }


    function submitAddMovieForm() {
        // 获取表单数据
        const form = document.getElementById('addMovieFormData');
        const formData = new FormData(form);

        // 发送 POST 请求到后端
        fetch('/admin/addMovie', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(Object.fromEntries(formData))
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('电影添加成功');
                    // 隐藏新增表单
                    document.getElementById('addMovieForm').style.display = 'none';
                    // 刷新电影列表
                    searchMovies();
                } else {
                    alert('电影添加失败：' + data.message);
                }
            })
            .catch(error => {
                alert('请求出错：' + error.message);
            });
    }
</script>
</body>
</html>